package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.BuildArticleFreemakerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class BuildArticleFreemakerServiceImpl  implements BuildArticleFreemakerService {


    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 根据文章内容生成文章详情静态页面
     * @param article
     * @param content
     */
    @Override
    public void buildArticleToMinio(ApArticle article, String content) throws IOException, TemplateException {
        //1.校验参数
        if(StringUtils.isBlank(content)){
            throw new RuntimeException("内容为空...");
        }
        //2.基于模板技术生成页面
        Map map = new HashMap<>();
        map.put("content", JSON.parseArray(content));
        Template template = configuration.getTemplate("article.ftl");
        StringWriter out = new StringWriter();
        template.process(map,out);

        //3.把页面存储到minio中
        InputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());
        String staticUrl = fileStorageService.uploadHtmlFile(null, article.getId() + ".html", inputStream);

        //4.把上传的staticUrl存储到article表中
        article.setStaticUrl(staticUrl);
        apArticleMapper.updateById(article);


        //todo 5.同步文章数据到ES中  （1.文章微服务再审核完成文章后，需要同步es数据-kafka进行消息的发送即可）
        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(article,searchArticleVo);
        searchArticleVo.setContent(content);
        System.out.println("searchArticleVo-"+searchArticleVo);
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC,JSON.toJSONString(searchArticleVo));
    }
}
